package org.zls.client;

import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.ClickListener;
import com.google.gwt.user.client.ui.Composite;
import com.google.gwt.user.client.ui.HorizontalPanel;
import com.google.gwt.user.client.ui.KeyboardListener;
import com.google.gwt.user.client.ui.MultiWordSuggestOracle;
import com.google.gwt.user.client.ui.SuggestBox;
import com.google.gwt.user.client.ui.SuggestionEvent;
import com.google.gwt.user.client.ui.SuggestionHandler;
import com.google.gwt.user.client.ui.VerticalPanel;
import com.google.gwt.user.client.ui.Widget;

/*
 * TODO: Should refactor this so we can reuse the search box. TODO: We should
 * make sure to have searches add to history.
 */
public abstract class SearchBox extends Composite {

	private Button button;
	private SuggestBox searchbox;
	private HorizontalPanel panel;
	private static final int MAX_SUGGEST = 20;

	public SearchBox() {

		panel = new HorizontalPanel();

		initSearchBox();
		initSearchButton();

		panel.setVerticalAlignment(VerticalPanel.ALIGN_BOTTOM);
		panel.setSpacing(MAX_SUGGEST);
		panel.add(searchbox);
		panel.add(button);

		initWidget(panel);
	}

	public abstract void handleSearch(String query);
	public abstract MultiWordSuggestOracle populateSuggestBox();

	public void initSearchBox() {
		searchbox = new SuggestBox(populateSuggestBox());
		searchbox.setLimit(MAX_SUGGEST);

		searchbox.addEventHandler(new SuggestionHandler() {

			public void onSuggestionSelected(SuggestionEvent suggestion) {

				handleSearch(suggestion.getSelectedSuggestion()
						.getReplacementString());
			}
		});
	}

	public void initSearchButton() {
		button = new Button("Search");

		button.addKeyboardListener(new KeyboardListener() {

			public void onKeyDown(Widget arg0, char arg1, int arg2) {
			}

			public void onKeyPress(Widget arg0, char arg1, int arg2) {
				if (arg1 == KEY_ENTER) {
					handleSearch(searchbox.getText());
				} else if (arg1 == KEY_TAB) {
					button.setFocus(true);
				}
			}

			public void onKeyUp(Widget arg0, char arg1, int arg2) {
			}
		});

		button.addClickListener(new ClickListener() {

			public void onClick(Widget arg0) {
				handleSearch(searchbox.getText());
			}

		});
	}
}
